/*
 * @Author: 肖思汗 
 * @Date: 2020-02-14 00:36:45 
 * @Last Modified by: 肖思汗
 * @Last Modified time: 2020-04-13 23:11:10
 */
import * as THREE from 'three';

const creatPoints = (() => {

    let canvas = document.createElement('canvas'); // 创建一个canvas 用于绘制文字纹理
    canvas.width = 1024;
    canvas.height = 1024;

    // document.body.appendChild(canvas);

    var ctx = canvas.getContext('2d');
    ctx.font = '40px arial';
    ctx.fillStyle = '#ffffff';
    ctx.textAlign = 'left';

    return (text = 'pointsText') => {
        let points = new THREE.Points();
        points.text = text;
        points.textColor = '#ffffff';
        points.textAlign = 'left';
        points.renderOrder = 2; // 设置渲染顺序在 渲染在最前面

        points.geometry.setAttribute('position', new THREE.Float32BufferAttribute([0, 0, 0], 3));
        points.material.map = new THREE.Texture(canvas);
        points.material.map.repeat.set(1, 1);
        points.material.map.offset.set(0, 0); // 纹理的偏移量
        points.material.transparent = true;
        points.material.sizeAttenuation = false; // 关闭近大远小的投影计算
        points.material.depthTest = false; // 不进行深度测试 绘制在最前面
        points.material.alphaTest = 0.1;
        points.material.size = 500;
        points.material.text = '';
        points.material.textAlign = '';
        points.material.textColor = '';
        points.material.fontSize = '';

        points.onBeforeRender = function(renderer, scene, carame, geometry, material) {

            // 有任意一个参数改变都需要重新绘制纹理
            if (
                material.text !== this.text ||
                material.textAlign !== this.textAlign ||
                material.textColor !== this.textColor ||
                material.fontSize !== this.fontSize
            ) {
                material.text = this.text;
                material.textAlign = this.textAlign;
                material.textColor = this.textColor;
                material.fontSize = this.fontSize;

                ctx.clearRect(0, 0, 1024, 1024);

                ctx.textAlign = this.textAlign;

                ctx.fillStyle = this.textColor;

                ctx.font = `${this.fontSize}px arial`;

                this.text.split('\n').map((t, i) => {
                    ctx.fillText(t, 512, (i + 0.5) * this.fontSize + 512);
                });

                points.material.map.needsUpdate = true;
            }
        };

        return points;

    };
})();

export default creatPoints;